package com.health.banner.controller;

import java.util.List;
import java.util.Map;

import com.health.common.constant.CacheConstants;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.health.common.annotation.Log;
import com.health.common.core.controller.BaseController;
import com.health.common.core.domain.AjaxResult;
import com.health.common.enums.BusinessType;
import com.health.banner.domain.ContentBanner;
import com.health.banner.service.IContentBannerService;
import com.health.common.utils.poi.ExcelUtil;
import com.health.common.core.page.TableDataInfo;

/**
 * 广告管理Controller
 * 
 * @author moxxie
 * @date 2025-10-27
 */
@RestController
@RequestMapping("/banner/banner")
public class ContentBannerController extends BaseController
{
    @Autowired
    private IContentBannerService contentBannerService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询广告管理列表
     */
    @PreAuthorize("@ss.hasPermi('banner:banner:list')")
    @GetMapping("/list")
    public TableDataInfo list(ContentBanner contentBanner)
    {
        startPage();
        List<ContentBanner> list = contentBannerService.selectContentBannerList(contentBanner);
        return getDataTable(list);
    }

    /**
     * 导出广告管理列表
     */
    @PreAuthorize("@ss.hasPermi('banner:banner:export')")
    @Log(title = "广告管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ContentBanner contentBanner)
    {
        List<ContentBanner> list = contentBannerService.selectContentBannerList(contentBanner);
        ExcelUtil<ContentBanner> util = new ExcelUtil<ContentBanner>(ContentBanner.class);
        util.exportExcel(response, list, "广告管理数据");
    }

    /**
     * 获取广告管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('banner:banner:query')")
    @GetMapping(value = "/{bannerId}")
    public AjaxResult getInfo(@PathVariable("bannerId") Long bannerId)
    {
        return success(contentBannerService.selectContentBannerByBannerId(bannerId));
    }

    /**
     * 新增广告管理
     */
    @PreAuthorize("@ss.hasPermi('banner:banner:add')")
    @Log(title = "广告管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ContentBanner contentBanner)
    {

        redisTemplate.opsForSet().add(CacheConstants.TMP_VALID_FILE_SET, contentBanner.getImageUrl());
        return toAjax(contentBannerService.insertContentBanner(contentBanner));
    }

    /**
     * 修改广告管理
     */
    @PreAuthorize("@ss.hasPermi('banner:banner:edit')")
    @Log(title = "广告管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ContentBanner contentBanner)
    {
        redisTemplate.opsForSet().add(CacheConstants.TMP_VALID_FILE_SET, contentBanner.getImageUrl());
        return toAjax(contentBannerService.updateContentBanner(contentBanner));
    }

    /**
     * 删除广告管理
     */
    @PreAuthorize("@ss.hasPermi('banner:banner:remove')")
    @Log(title = "广告管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{bannerIds}")
    public AjaxResult remove(@PathVariable Long[] bannerIds)
    {
        return toAjax(contentBannerService.deleteContentBannerByBannerIds(bannerIds));
    }

    /**
     * 批量修改状态
     */
    @PutMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody Map<String, Object> params) {
        try {
            // 1. 参数校验
            if (params == null || !params.containsKey("bannerIds") || !params.containsKey("status")) {
                return AjaxResult.error("缺少必要参数");
            }

            // 2. 处理bannerIds
            Object bannerIdsObj = params.get("bannerIds");
            if (!(bannerIdsObj instanceof List)) {
                return AjaxResult.error("bannerIds必须是数组");
            }

            List<?> idList = (List<?>) bannerIdsObj;
            if (idList.isEmpty()) {
                return AjaxResult.error("请至少选择一条记录");
            }

            Long[] bannerIds = idList.stream()
                    .map(id -> {
                        try {
                            return Long.parseLong(id.toString());
                        } catch (NumberFormatException e) {
                            throw new IllegalArgumentException("无效的ID格式: " + id);
                        }
                    })
                    .toArray(Long[]::new);

            // 3. 处理status
            Object statusObj = params.get("status");
            String status = statusObj != null ? statusObj.toString() : null;

            if (status == null || (!"0".equals(status) && !"1".equals(status))) {
                return AjaxResult.error("状态值只能是0或1");
            }

            // 4. 调用服务
            return toAjax(contentBannerService.updateContentBannerStatus(bannerIds, status));

        } catch (IllegalArgumentException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            return AjaxResult.error("系统错误: " + e.getMessage());
        }
    }
}
